package com.ailianlian.ablecisi.viewmodel;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.ailianlian.ablecisi.baseclass.BaseRepository;
import com.ailianlian.ablecisi.baseclass.BaseViewModel;
import com.ailianlian.ablecisi.pojo.entity.Article;
import com.ailianlian.ablecisi.pojo.entity.Comment;
import com.ailianlian.ablecisi.repository.ArticleRepository;
import com.ailianlian.ablecisi.utils.LoginInfoUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 文章详情的ViewModel
 */
public class ArticleViewModel extends BaseViewModel {


    private MutableLiveData<Article> article; // 文章详情
    private MutableLiveData<List<Article>> relatedArticles; // 相关文章列表
    private MutableLiveData<List<Comment>> commentsGlobal; // 评论列表
    private MutableLiveData<Boolean> isLoading; // 是否正在加载文章详情
    private MutableLiveData<Boolean> isCommentLoading; // 是否正在加载评论
    private MutableLiveData<String> errorMessage; // 错误信息
    private MutableLiveData<Boolean> commentSuccess; // 评论是否成功
    private MutableLiveData<Boolean> isFollowing; // 是否关注作者
    private ArticleRepository articleRepository; // 文章仓库

    public ArticleViewModel(@NonNull Application application) {
        super(application, new MutableLiveData<>());
        article = new MutableLiveData<>();
        relatedArticles = new MutableLiveData<>(new ArrayList<>());
        isLoading = new MutableLiveData<>(false);
        isCommentLoading = new MutableLiveData<>(false);
        errorMessage = new MutableLiveData<>();
        commentSuccess = new MutableLiveData<>(false);
        articleRepository = new ArticleRepository(application);
        isFollowing = new MutableLiveData<>(false);
        commentsGlobal = new MutableLiveData<>(new ArrayList<>());
    }

    /**
     * 加载文章详情
     * @param articleId 文章ID
     */
    public void loadArticle(String articleId) {
        isLoading.setValue(true);
        // 通过repository加载文章数据
        articleRepository.loadArticle(articleId, new BaseRepository.DataCallback<Article>() {
            @Override
            public void onSuccess(Article loadedArticle) {
                isLoading.postValue(false);
                if (loadedArticle != null) {
                    article.postValue(loadedArticle);
                } else {
                    errorMessage.postValue("文章加载失败，请稍后再试");
                }
            }

            @Override
            public void onError(String error) {
                isLoading.postValue(false);
                errorMessage.postValue(error);
            }

            @Override
            public void onNetworkError() {
                isLoading.postValue(false);
                errorMessage.postValue("网络错误，请检查您的网络连接");
            }
        });

        loadComments(articleId); // 加载评论
    }

    /**
     * 加载相关文章
     */
    public void loadRelatedArticles(String articleId) {
        articleRepository.loadRelatedArticles(articleId, new BaseRepository.DataCallback<List<Article>>() {
            @Override
            public void onSuccess(List<Article> articles) {
                if (articles != null && !articles.isEmpty()) {
                    relatedArticles.postValue(articles);
                } else {
                    relatedArticles.postValue(new ArrayList<>());
                }
            }

            @Override
            public void onError(String error) {
                errorMessage.postValue(error);
            }

            @Override
            public void onNetworkError() {
                errorMessage.postValue("网络错误，请检查您的网络连接");
            }
        });

    }

    /**
     * 点赞文章
     */
    public void likeArticle() {
        Article currentArticle = article.getValue();
        if (currentArticle != null) {
            boolean isCurrentlyLiked = currentArticle.getLiked();
            currentArticle.setLiked(!isCurrentlyLiked);
            
            // 更新点赞数
            int currentLikes = currentArticle.getLikeCount();
            currentArticle.setLikeCount(isCurrentlyLiked ? currentLikes - 1 : currentLikes + 1);
            
            article.setValue(currentArticle);
        }
    }

    /**
     * 收藏文章
     */
    public void bookmarkArticle() {
        Article currentArticle = article.getValue();
        if (currentArticle != null) {
            currentArticle.setBookmarked(!currentArticle.getBookmarked());
            article.setValue(currentArticle);
        }
    }

    /**
     * 添加评论
     * @param content 评论内容
     * @param parentCommentId 父评论ID，如果是回复评论的话
     */
    public void addComment(String content, String parentCommentId) {
        if (content == null || content.trim().isEmpty()) {
            errorMessage.setValue("评论内容不能为空");
            return;
        }
        
        isCommentLoading.setValue(true);

    }

    /**
     * 点赞评论
     * @param commentId 评论ID
     */
    public void likeComment(String commentId) {
        Article currentArticle = article.getValue();
        if (currentArticle != null) {
            List<Comment> comments = currentArticle.getComments();
            for (Comment comment : comments) {
                // 检查主评论
                if (comment.getId().equals(commentId)) {
                    toggleCommentLike(comment);
                    article.setValue(currentArticle);
                    return;
                }
                
                // 检查回复评论
                for (Comment reply : comment.getReplies()) {
                    if (reply.getId().equals(commentId)) {
                        toggleCommentLike(reply);
                        article.setValue(currentArticle);
                        return;
                    }
                }
            }
        }
    }

    /**
     * 切换评论点赞状态
     * @param comment 评论对象
     */
    private void toggleCommentLike(Comment comment) {
        boolean isCurrentlyLiked = comment.getLiked();
        comment.setLiked(!isCurrentlyLiked);
        
        // 更新点赞数
        int currentLikes = comment.getLikeCount();
        comment.setLikeCount(isCurrentlyLiked ? currentLikes - 1 : currentLikes + 1);
    }

    public LiveData<Article> getArticle() {
        return article;
    }

    public LiveData<List<Article>> getRelatedArticles() {
        return relatedArticles;
    }

    public LiveData<Boolean> getIsLoading() {
        return isLoading;
    }

    public LiveData<Boolean> getIsCommentLoading() {
        return isCommentLoading;
    }

    public LiveData<String> getErrorMessage() {
        return errorMessage;
    }

    public LiveData<Boolean> getCommentSuccess() {
        return commentSuccess;
    }

    public LiveData<Boolean> getIsFollowing() {
        return isFollowing;
    }

    public LiveData<List<Comment>> getCommentsGlobal() {
        return commentsGlobal;
    }

    public void followAuthor(boolean isFollowing) {
        Article currentArticle = article.getValue();
        if (currentArticle != null) {
            String authorId = currentArticle.getAuthorId();
            String userId = LoginInfoUtil.getUserId(getAppContext());
            if (authorId.equals(userId)) {
                errorMessage.postValue("不能关注自己");
                return;
            }

            articleRepository.followAuthor(userId, authorId, isFollowing, new BaseRepository.DataCallback<Boolean>() {
                @Override
                public void onSuccess(Boolean success) {
                    if (success) {
                        System.out.println("关注状态更新成功");// 更新UI状态或通知用户
                    } else {
                        errorMessage.postValue("关注状态更新失败，请稍后再试");
                    }
                }

                @Override
                public void onError(String error) {
                    errorMessage.postValue(error);
                }

                @Override
                public void onNetworkError() {
                    errorMessage.postValue("网络错误，请检查您的网络连接");
                }
            });
        }
    }

    public void loadFollowStatus(String articleId) {
        Article currentArticle = article.getValue();
        System.out.println(currentArticle);
        if (currentArticle == null) {
            // 如果当前文章为空，等待加载完成后再尝试获取关注状态
            return;
        }
        String authorId = currentArticle.getAuthorId();
        String userId = LoginInfoUtil.getUserId(getAppContext());
        System.out.println("当前用户ID: " + userId + " 文章作者ID: " + authorId);
        articleRepository.loadFollowStatus(userId, authorId, new BaseRepository.DataCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean isFollowingStatus) {
                isFollowing.postValue(isFollowingStatus);
                System.out.println("关注状态加载成功: " + isFollowingStatus);
            }

            @Override
            public void onError(String error) {
                errorMessage.postValue(error);
                System.out.println("关注状态加载失败: " + error);
            }

            @Override
            public void onNetworkError() {
                errorMessage.postValue("网络错误，请检查您的网络连接");
                System.out.println("关注状态加载网络错误");
            }
        });

    }

    public void loadComments(String articleId) {
        isCommentLoading.setValue(true);
        articleRepository.loadComments(articleId, new BaseRepository.DataCallback<List<Comment>>() {
            @Override
            public void onSuccess(List<Comment> comments) {
                if (comments != null && !comments.isEmpty()) {
                    commentsGlobal.postValue(comments);
                    isCommentLoading.postValue(false);
                    commentSuccess.postValue(true);
                    System.out.println("评论加载成功，评论数量: " + comments.size());
                } else {
                    errorMessage.postValue("没有评论数据");
                    isCommentLoading.postValue(false);
                }
            }

            @Override
            public void onError(String error) {
                errorMessage.postValue(error);
                isCommentLoading.postValue(false);
            }

            @Override
            public void onNetworkError() {
                errorMessage.postValue("网络错误，请检查您的网络连接");
                isCommentLoading.postValue(false);
            }
        });
    }


}